package o2o.task.user;

import com.jinyou.utils.common.DateUtils;
import o2o.cache.user.UserInfoExtraMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.system.data.SYS_SETTINGS;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户最后在线时间
 */

@Component
public class UserLastOnlineTimeTask {

    private static ConcurrentHashMap<String, Long> lastOnlineTimeMap = new ConcurrentHashMap<>();

    /**
     * 增加用户的最后在线时间
     *
     * @param username
     */
    public static void addUserLastOnlineTime(String username) {
        if (StringUtils.isNotEmpty(username)) {
            lastOnlineTimeMap.put(username, DateUtils.getCurrTime());
        }
    }

    // 每间隔一个小时更新一次用户最后在线时间，并清除缓存数据
    @Scheduled(cron = "0 0/20 * * * ? ")
    private void dealUserLastOnlineToDB() {
        Map<String, Long> dealMap = lastOnlineTimeMap;
        if (dealMap != null && !dealMap.isEmpty()) {
            for (String username : dealMap.keySet()) {
                Long time = dealMap.get(username);
                if (time == null || time < 1) {
                    continue;
                }
                StringBuffer sql = new StringBuffer();
                sql.append(" update ").append(PojoTables.USER_INFO_EXTRA)
                        .append(" set lastOnlineTime = ").append(time)
                        .append(" where username ='").append(username).append("' and delFlag = 0");
                try {
                    UserDaoSql.getInstance().executeBySql(sql.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UserInfoExtraMemory.getInstance().modifyLastOnlineTime(username, time);
                UserInfoMemory.getInstance().updateOnlineTime(username, new Date(time));
            }
        }
        lastOnlineTimeMap.clear();
    }

}
